'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';

interface InventoryCheck {
  id: number;
  checkNumber: string;
  checkDate: string;
  status: 'draft' | 'in_progress' | 'completed' | 'cancelled';
  totalItems: number;
  checkedItems: number;
  discrepancies: number;
  notes: string | null;
  createdAt: string;
}

export default function InventoryCheckPage() {
  const [checks, setChecks] = useState<InventoryCheck[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetchChecks();
  }, []);

  const fetchChecks = async () => {
    try {
      const response = await fetch('/api/inventory/check');
      if (response.ok) {
        const data = await response.json();
        setChecks(Array.isArray(data) ? data : []);
      } else {
        console.error('获取盘点列表失败:', await response.json());
        setChecks([]);
      }
    } catch (error) {
      console.error('获取盘点列表失败:', error);
      setChecks([]);
    } finally {
      setLoading(false);
    }
  };

  const handleCreateCheck = async () => {
    try {
      const response = await fetch('/api/inventory/check', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      });

      if (response.ok) {
        const newCheck = await response.json();
        // 跳转到盘点详情页面
        window.location.href = `/inventory/check/${newCheck.id}`;
      } else {
        const errorData = await response.json();
        alert('创建盘点单失败: ' + (errorData.error || '未知错误'));
      }
    } catch (error) {
      console.error('创建盘点单失败:', error);
      alert('创建盘点单失败，请重试');
    }
  };

  const getStatusText = (status: string) => {
    const statusMap = {
      'draft': '草稿',
      'in_progress': '进行中',
      'completed': '已完成',
      'cancelled': '已取消'
    };
    return statusMap[status as keyof typeof statusMap] || status;
  };

  const getStatusColor = (status: string) => {
    const colorMap = {
      'draft': 'bg-gray-100 text-gray-800',
      'in_progress': 'bg-blue-100 text-blue-800',
      'completed': 'bg-green-100 text-green-800',
      'cancelled': 'bg-red-100 text-red-800'
    };
    return colorMap[status as keyof typeof colorMap] || 'bg-gray-100 text-gray-800';
  };

  const getProgressPercentage = (check: InventoryCheck) => {
    if (check.totalItems === 0) return 0;
    return Math.round((check.checkedItems / check.totalItems) * 100);
  };

  if (loading) return <div className="p-8">加载中...</div>;

  return (
    <div className="p-8">
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <Link href="/inventory" className="text-gray-600 hover:text-gray-900">
            ← 返回库存管理
          </Link>
          <h1 className="text-3xl font-bold">库存盘点</h1>
        </div>
        <button
          onClick={handleCreateCheck}
          className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
        >
          新建盘点
        </button>
      </div>

      {checks.length === 0 ? (
        <div className="bg-white rounded-lg shadow-md p-12 text-center">
          <div className="text-gray-400 text-6xl mb-4">📦</div>
          <h3 className="text-lg font-semibold text-gray-900 mb-2">暂无盘点记录</h3>
          <p className="text-gray-500 mb-6">点击"新建盘点"开始您的第一次库存盘点</p>
          <button
            onClick={handleCreateCheck}
            className="px-6 py-3 bg-blue-600 text-white rounded-md hover:bg-blue-700"
          >
            开始盘点
          </button>
        </div>
      ) : (
        <>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-6 mb-6">
            <div className="bg-white rounded-lg shadow p-4 text-center">
              <div className="text-2xl font-bold text-gray-800">{checks.length}</div>
              <div className="text-sm text-gray-600">总盘点单数</div>
            </div>
            <div className="bg-white rounded-lg shadow p-4 text-center">
              <div className="text-2xl font-bold text-blue-600">
                {checks.filter(c => c.status === 'in_progress').length}
              </div>
              <div className="text-sm text-gray-600">进行中</div>
            </div>
            <div className="bg-white rounded-lg shadow p-4 text-center">
              <div className="text-2xl font-bold text-green-600">
                {checks.filter(c => c.status === 'completed').length}
              </div>
              <div className="text-sm text-gray-600">已完成</div>
            </div>
            <div className="bg-white rounded-lg shadow p-4 text-center">
              <div className="text-2xl font-bold text-orange-600">
                {checks.reduce((sum, c) => sum + c.discrepancies, 0)}
              </div>
              <div className="text-sm text-gray-600">总差异数</div>
            </div>
          </div>

          <div className="bg-white rounded-lg shadow overflow-hidden">
            <table className="min-w-full divide-y divide-gray-200">
              <thead className="bg-gray-50">
                <tr>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    盘点单号
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    盘点日期
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    状态
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    进度
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    差异
                  </th>
                  <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className="bg-white divide-y divide-gray-200">
                {checks.map((check) => (
                  <tr key={check.id}>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
                      {check.checkNumber}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {new Date(check.checkDate).toLocaleDateString('zh-CN')}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${getStatusColor(check.status)}`}>
                        {getStatusText(check.status)}
                      </span>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap">
                      <div className="flex items-center">
                        <div className="w-20 bg-gray-200 rounded-full h-2 mr-2">
                          <div 
                            className="bg-blue-600 h-2 rounded-full" 
                            style={{ width: `${getProgressPercentage(check)}%` }}
                          />
                        </div>
                        <span className="text-sm text-gray-600">
                          {getProgressPercentage(check)}%
                        </span>
                      </div>
                      <div className="text-xs text-gray-500">
                        {check.checkedItems}/{check.totalItems} 项
                      </div>
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                      {check.discrepancies > 0 ? (
                        <span className="text-red-600 font-medium">{check.discrepancies} 处</span>
                      ) : (
                        <span className="text-green-600">无差异</span>
                      )}
                    </td>
                    <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                      <Link 
                        href={`/inventory/check/${check.id}`}
                        className="text-blue-600 hover:text-blue-900 mr-3"
                      >
                        查看详情
                      </Link>
                      {check.status === 'draft' && (
                        <button className="text-red-600 hover:text-red-900">
                          取消
                        </button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      )}

      <div className="mt-8 bg-blue-50 border border-blue-200 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-blue-800 mb-2">库存盘点说明</h3>
        <ul className="text-sm text-blue-700 space-y-1">
          <li>• 库存盘点用于核对实际库存数量与系统记录的差异</li>
          <li>• 新建盘点时会自动包含所有当前库存商品</li>
          <li>• 盘点过程中需要逐一核对每个商品的实际情况</li>
          <li>• 盘点完成后可以生成差异报告并调整库存</li>
          <li>• 建议定期进行库存盘点以保证数据准确性</li>
        </ul>
      </div>
    </div>
  );
}